/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MainFrame.java
 *
 * Created on May 29, 2012, 12:05:23 AM
 */
package gui;

import java.awt.Image;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.text.BadLocationException;

/**
 *
 * @author HoangLiem
 */
public class MainFrame extends javax.swing.JFrame {

    /** Creates new form MainFrame */
    public MainFrame() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jPanel1 = new javax.swing.JPanel();
        jToolBar = new javax.swing.JToolBar();
        jbtExec = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JToolBar.Separator();
        jbtConnect = new javax.swing.JButton();
        jSeparator2 = new javax.swing.JToolBar.Separator();
        jLabel1 = new javax.swing.JLabel();
        jcbDatabaseName = new javax.swing.JComboBox();
        jPanel2 = new javax.swing.JPanel();
        jSplitPaneBody = new javax.swing.JSplitPane();
        jTpTableData = new javax.swing.JTabbedPane();
        jScrollPane3 = new javax.swing.JScrollPane();
        jtaMessage = new javax.swing.JTextArea();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane4 = new javax.swing.JScrollPane();
        jTableData = new javax.swing.JTable();
        jTabbedPaneQuery = new javax.swing.JTabbedPane();
        jScrollPane2 = new javax.swing.JScrollPane();
        jtaQuery = new javax.swing.JTextArea();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItemClose = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(300, 200));
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jToolBar.setRollover(true);

        jbtExec.setToolTipText("Exec query below");
        jbtExec.setFocusable(false);
        jbtExec.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jbtExec.setMaximumSize(new java.awt.Dimension(40, 40));
        jbtExec.setPreferredSize(new java.awt.Dimension(40, 40));
        jbtExec.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jbtExec.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtExecActionPerformed(evt);
            }
        });
        jToolBar.add(jbtExec);
        jToolBar.add(jSeparator1);

        jbtConnect.setToolTipText("Connect to server host");
        jbtConnect.setFocusable(false);
        jbtConnect.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jbtConnect.setMaximumSize(new java.awt.Dimension(40, 40));
        jbtConnect.setPreferredSize(new java.awt.Dimension(40, 40));
        jbtConnect.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jbtConnect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtConnectActionPerformed(evt);
            }
        });
        jToolBar.add(jbtConnect);
        jToolBar.add(jSeparator2);

        jLabel1.setText("  Database : ");
        jToolBar.add(jLabel1);

        jcbDatabaseName.setMaximumSize(new java.awt.Dimension(150, 20));
        jcbDatabaseName.setPreferredSize(new java.awt.Dimension(150, 20));
        jToolBar.add(jcbDatabaseName);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jToolBar, javax.swing.GroupLayout.PREFERRED_SIZE, 433, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(140, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jToolBar, javax.swing.GroupLayout.DEFAULT_SIZE, 34, Short.MAX_VALUE)
                .addContainerGap())
        );

        jSplitPaneBody.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        jSplitPaneBody.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
        jSplitPaneBody.setResizeWeight(0.6);
        jSplitPaneBody.setAutoscrolls(true);
        jSplitPaneBody.setMinimumSize(new java.awt.Dimension(250, 250));

        jTpTableData.setAutoscrolls(true);
        jTpTableData.setMinimumSize(new java.awt.Dimension(100, 100));
        jTpTableData.setPreferredSize(new java.awt.Dimension(400, 200));

        jtaMessage.setColumns(20);
        jtaMessage.setEditable(false);
        jtaMessage.setRows(5);
        jScrollPane3.setViewportView(jtaMessage);

        jTpTableData.addTab("Messages", jScrollPane3);

        jPanel3.setAutoscrolls(true);

        jTableData.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        jTableData.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        jTableData.setRowHeight(10);
        jScrollPane4.setViewportView(jTableData);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 570, Short.MAX_VALUE)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 145, Short.MAX_VALUE)
        );

        jTpTableData.addTab("Table Data", jPanel3);

        jSplitPaneBody.setBottomComponent(jTpTableData);

        jTabbedPaneQuery.setMinimumSize(new java.awt.Dimension(150, 150));

        jtaQuery.setColumns(20);
        jtaQuery.setRows(10);
        jtaQuery.setMinimumSize(new java.awt.Dimension(100, 100));
        jScrollPane2.setViewportView(jtaQuery);

        jTabbedPaneQuery.addTab("Query", jScrollPane2);

        jSplitPaneBody.setTopComponent(jTabbedPaneQuery);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jSplitPaneBody, javax.swing.GroupLayout.DEFAULT_SIZE, 577, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPaneBody, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 330, Short.MAX_VALUE)
        );

        jMenu1.setText("  File  ");

        jMenuItemClose.setText("Close");
        jMenuItemClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemCloseActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItemClose);

        jMenuBar1.add(jMenu1);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    Socket socket = null;
    
    private void connectServerHost() {
        ConnectInfoDialog dialog = showConnectDialog();
        if (dialog.isCancelClicked()) {
            JOptionPane.showMessageDialog(this, "Not connected to server host");
            this.jbtExec.setEnabled(false);
            this.jbtConnect.setEnabled(true);
        } else {
            this.jbtExec.setEnabled(true);
            this.jbtConnect.setEnabled(false);
            socket = dialog.getSocket();
            initDatabaseNames(dialog.getDatabaseNames());
        }
    }
    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        // TODO add your handling code here:
        initToolBarTable();
        connectServerHost();
    }//GEN-LAST:event_formWindowOpened
    
    private ConnectInfoDialog showConnectDialog() {
        ConnectInfoDialog dialog = new ConnectInfoDialog(this, true);
        JFrameLocation.centerOnScreen(dialog);
        dialog.setVisible(true);
        return dialog;
    }
    private void jMenuItemCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemCloseActionPerformed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_jMenuItemCloseActionPerformed
    
    private String getQuery() {
        String query = jtaQuery.getText();
        int totalLines = jtaQuery.getLineCount();
        String line = "";
        for (int i = 0; i < totalLines; i++) {
            try {
                int start = jtaQuery.getLineStartOffset(i);
                int end = jtaQuery.getLineEndOffset(i);
                line = line + " " + query.substring(start, end);
                
            } catch (BadLocationException ex) {
                Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        line = line.replace("\n", "");
        line = line.trim();
        return line;
    }
    
    private void execQuery() {
        OutputStream os = null;
        try {
            // TODO add your handling code here:
            String databaseName = (String) jcbDatabaseName.getSelectedItem();
            String query = getQuery();//jtaQuery.getText().trim();
            if (!query.equals("")) {
                os = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(socket.getOutputStream());
                BufferedWriter bw = new BufferedWriter(osw);
                bw.write("query");
                bw.newLine();
                bw.flush();
                bw.write(databaseName);
                bw.newLine();
                bw.flush();
                bw.write(query);
                bw.newLine();
                bw.flush();
                //Cai đat 1 tien trinh lang nghe thông điệp tra ve
                new ListenResult(socket, query, jTpTableData, jtaMessage, jTableData);
            } else {
                jtaMessage.setText("Query must be not empty");
            }
        } catch (IOException ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    private void jbtExecActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtExecActionPerformed
        
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            
            @Override
            public void run() {
                execQuery();
                throw new UnsupportedOperationException("Not supported yet.");
            }
        });
    }//GEN-LAST:event_jbtExecActionPerformed

    private void jbtConnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtConnectActionPerformed
        // TODO add your handling code here:
        connectServerHost();
    }//GEN-LAST:event_jbtConnectActionPerformed
    void initDatabaseNames(ArrayList<String> databaseNames) {
        if (databaseNames != null && !databaseNames.isEmpty()) {
            for (int i = 0; i < databaseNames.size(); i++) {
                jcbDatabaseName.addItem(databaseNames.get(i));
            }
        }
    }
    
    void initToolBarTable() {
        //this.jtoolBarDataTable.setVisible(true);  
        Image img1 = new ImageIcon("resources/exec.png").getImage();
        Image resizedImage1 = img1.getScaledInstance(jbtExec.getWidth(), jbtExec.getHeight(), Image.SCALE_DEFAULT);
        jbtExec.setIcon(new ImageIcon(resizedImage1));
        Image img2 = new ImageIcon("resources/connect.png").getImage();
        Image resizedImage2 = img2.getScaledInstance(jbtConnect.getWidth(), jbtConnect.getHeight(), Image.SCALE_DEFAULT);
        jbtConnect.setIcon(new ImageIcon(resizedImage2));
        
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            
            public void run() {
                new MainFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItemClose;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JToolBar.Separator jSeparator1;
    private javax.swing.JToolBar.Separator jSeparator2;
    private javax.swing.JSplitPane jSplitPaneBody;
    private javax.swing.JTabbedPane jTabbedPaneQuery;
    private javax.swing.JTable jTableData;
    private javax.swing.JToolBar jToolBar;
    private javax.swing.JTabbedPane jTpTableData;
    private javax.swing.JButton jbtConnect;
    private javax.swing.JButton jbtExec;
    private javax.swing.JComboBox jcbDatabaseName;
    private javax.swing.JTextArea jtaMessage;
    private javax.swing.JTextArea jtaQuery;
    // End of variables declaration//GEN-END:variables
}
